package cn.tomoya.module.api.controller;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.tomoya.common.BaseController;
import cn.tomoya.common.config.SiteConfig;
import cn.tomoya.exception.ApiException;
import cn.tomoya.exception.Result;
import cn.tomoya.module.security.JwtTokenUtil;
import cn.tomoya.module.security.JwtUser;
import cn.tomoya.module.security.core.MyUserDetailService;
import cn.tomoya.module.security.entity.Role;
import cn.tomoya.module.security.service.RoleService;
import cn.tomoya.module.topic.entity.Topic;
import cn.tomoya.module.topic.service.TopicService;
import cn.tomoya.module.user.entity.User;
import cn.tomoya.module.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * Created by tomoya.
 * Copyright (c) 2016, All Rights Reserved.
 * http://tomoya.cn
 */
@RestController
@Api(tags = "交流系统首页",description = "APP")
public class IndexApiController extends BaseController {

    @Autowired
    private TopicService topicService;
    @Autowired
    private SiteConfig siteConfig;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private MyUserDetailService myUserDetailService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDetailsService userDetailsService;


    /**
     * 话题列表接口
     * @param tab
     * @param p
     * @return
     * @throws ApiException
     */
    @ApiOperation(value = "交流系统首页数据",notes = "返回首页数据",response = Topic.class)
    @RequestMapping(value = "/api/index/{tab}/{size}/{p}",method = RequestMethod.GET)
//    @GetMapping("/index")
    public Result index(HttpServletRequest request,@PathVariable("tab")@ApiParam("最新tab=2,默认最热") String tab, @PathVariable("size")@ApiParam("每页显示条数")Integer size,@PathVariable("p")@ApiParam("页数") Integer p) throws ApiException {
        Page<Topic> page = topicService.page(p == null ? 1 : p, size, tab);
        Result result = new Result();

        String authorization = request.getHeader("Authorization");
        if(authorization!=null){
            JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(authorization);
            String tokenUserName = jwtUsr.getUsername();
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(tokenUserName);
            User user = userService.findByUsername(tokenUserName);
            String username = user.getUsername();
            if(username.equals(tokenUserName)){
                return result.success(page);
            } else{
                return result.error(400,"没有权限");
            }

        }else{
            return result.error(400,"没有权限");
        }

    }

    @ApiOperation(value = "用户登录接口",notes = "用户登录信息",httpMethod = "POST")
    @RequestMapping("/api/index/ssologin")
    public Result createAuthenticationToken(@ApiParam(value = "提交条件对象token:String", required = true)@RequestBody JSONObject tokenvo) throws AuthenticationException
    {
        String token =(String) tokenvo.get("token");

        Result result = new Result();
        JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(token);
        String tokenUserName = jwtUsr.getUsername();
        if(tokenUserName== null || "".equals(tokenUserName)){
//            跳转登录
            /*return render("/login");*/
            result.setDescription("没有登录");
            result.setCode(201);
            return  result;
        }
        User user = userService.findByUsername(tokenUserName);

        if(user == null){
            user = new User();
            Date now = new Date();
            user.setUsername(tokenUserName);
            user.setPassword(new BCryptPasswordEncoder().encode("abc123"));
            user.setInTime(now);
            user.setOrgname(jwtUsr.getOrgName());
            user.setNickname(jwtUsr.getNickName());
            user.setBzyId(jwtUsr.getId());


            Role role = roleService.findById(3);
            Set<Role> roles = new HashSet<>();
            roles.add(role);
            user.setRoles(roles);

            String avatarName = UUID.randomUUID().toString();
            user.setAvatar(siteConfig.getBaseUrl() + "static/images/avatar/" + avatarName + ".png");
            userService.save(user);
        }
        user.setNickname(jwtUsr.getNickName());
        user.setOrgname(jwtUsr.getOrgName());
        userService.updateUser(user);
        // Perform the security
        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),"abc123"));
        SecurityContextHolder.getContext().setAuthentication(authentication);


        return result.success(user) ;
    }
}
